# -*- coding: utf-8 -*-
import argparse
import datetime
import json
import os
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
import cv2

# 添加新的功能   给选项进行标记（画框），正确的标记绿框，错误的标记红框，生成一张新的图片，图片名命名为原图片加一个后缀
from control.Databasemanage import DatabaseManager
from socre.method_1_plus import solve_1


def contrast(correct_answers_with_index, img_path, detect_answer_1,
             rect_size=(50, 30)):
    # 将正确答案转换为字典以便快速查找
    correct_answers_dict = {index: (answer, score) for index, score, answer, _ in correct_answers_with_index}
    # 将检测到的答案转换为字典
    now_answers_dict_1 = {index: (answer, x) for index, _, _, _, _, x, answer, _, _ in detect_answer_1}
    # 读取图像
    image = cv2.imread(img_path)
    if image is None:
        # print("Image not found")
        return None, None, None, None, None

    # 复制图像进行操作，避免修改原图
    output_image = image.copy()

    correct_count_1, correct_count_2 = 0, 0
    s1, s2 = 0, 0
    correct_questions_1, incorrect_questions_1 = [], []

    for question, correct_answer in correct_answers_dict.items():
        # print(question, correct_answer)
        now_1 = now_answers_dict_1.get(question)

        check_and_mark_answer(output_image, now_1, correct_answer[0], correct_count_1, s1, correct_questions_1,
                              incorrect_questions_1, rect_size, (0, 255, 0), (0, 0, 255))
        # check_and_mark_answer(output_image, now_2, correct_answer, _s_1, _s_2, correct_count_2, s2, correct_questions_2,
        #                       incorrect_questions_2, rect_size, (0, 255, 0), (0, 0, 255))

    # 假设 output_image 是 PIL 图像对象，img_path 是图像保存的路径

    # 保存标记后的图像
    save_marked_image(output_image, img_path, "_plus")

    return True


def check_and_mark_answer(image, answer, correct_answer, correct_count, score_sum, correct_questions,
                          incorrect_questions, rect_size, green, red):
    if answer is not None and answer[0] == correct_answer:
        correct_count += 1
        for coordinates in answer[1]:  # 处理answer[1]中的每个坐标
            correct_questions.append((coordinates, answer[0]))
            draw_rectangle(image, coordinates, rect_size, green)
    elif answer is not None:
        for coordinates in answer[1]:  # 处理answer[1]中的每个坐标
            incorrect_questions.append((coordinates, answer[0], correct_answer))
            draw_rectangle(image, coordinates, rect_size, red)

def draw_rectangle(image, coordinates, rect_size, color):
    # 检查coordinates_list是否为空
    if not coordinates:
        # print("No coordinates to draw rectangles.")
        return
    # 确保coordinates是可迭代的，并且包含两个元素
    if isinstance(coordinates, (list, tuple)) and len(coordinates) == 2:
        # 将坐标转换为整数
        x, y = int(coordinates[0]), int(coordinates[1])
        # 计算矩形的左上角和右下角坐标
        top_left = (x - rect_size[0] // 2, y - rect_size[1] // 2)
        bottom_right = (x + rect_size[0] // 2, y + rect_size[1] // 2)
        # 绘制矩形
        cv2.rectangle(image, top_left, bottom_right, color, 2)
    else:
        pass
        # print("Invalid coordinates:", coordinates)

def calculate_accuracy(correct_count_1, correct_count_2, total_questions):
    if total_questions != 0:
        return correct_count_1 / total_questions, correct_count_2 / total_questions
    else:
        return -1, -1

def save_marked_image(image, img_path, suffix):
    # 获取文件的基本名称和扩展名
    base_name = os.path.basename(img_path)
    name_without_ext, ext = os.path.splitext(base_name)

    # 构建新的文件名
    new_name = name_without_ext + suffix + ext
    new_img_path = os.path.join(os.path.dirname(img_path), new_name)

    # 检查文件是否已存在
    if os.path.exists(new_img_path):
        # 如果文件存在，添加时间戳到现有文件名
        timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")
        new_name_with_timestamp = f"{name_without_ext}_{timestamp}{ext}"
        original_img_path = os.path.join(os.path.dirname(img_path), new_name_with_timestamp)
        # 重命名现有文件
        os.rename(new_img_path, original_img_path)

    # 保存新图像
    cv2.imwrite(new_img_path, image)

def process_file(img_path, standard_answers, subjectCode, studentId, paperId, answerQrcode, parent_answer_id):

    # 调用函数，传入参数组和备用参数组
    detect_answer_1 = solve_1(img_path, standard_answers, subjectCode, studentId, paperId, answerQrcode, parent_answer_id)
    # print(f"lende1:{len(detect_answer_1)}")
    # print(f"de1:{detect_answer_1}")
    try:
        contrast(standard_answers, img_path, detect_answer_1)
    except Exception as e:
        # 读取图像
        image = cv2.imread(img_path)
        # 复制图像进行操作，避免修改原图
        output_image = image.copy()
        # 保存标记后的图像
        save_marked_image(output_image, img_path, "_plus")
        print(f"Fail to deal with: {img_path}")

    # 初始化一个空列表来存储结果字符串
    result_list = []
    if detect_answer_1 is not None:
        if len(detect_answer_1) != 0:
            real_answers = detect_answer_1
            for answer in real_answers:
                answer_id = answer[0]
                subject_code = answer[1]
                student_id = answer[2]
                answer_standard = answer[3]
                answer_student = answer[6]
                paperId = answer[4]
                score = answer[7]
                parent_answer_id = answer[8]
                result_list.append(f"{answer_id}_{subject_code}_{student_id}_{answer_standard}_{answer_student}_{paperId}_{score}_{parent_answer_id}")
                # print(f"{answer_id}_{subject_code}_{student_id}_{answer_standard}_{answer_student}_{paperId}_{score}")
        else:

            print(f"Fail to deal with: {img_path}")

    return result_list


def start_processing(image_paths, ytoken, ip):
    main(image_paths, ytoken, ip)

def main(image_paths, ytoken, ip):
    start_time = time.time()
    # 使用线程池并发处理文件
    max_workers = min(100, os.cpu_count() or 1)  # 设置线程数量，您可以根据需要调整
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = {executor.submit(process_file, img_path, ytoken, ip): img_path for img_path in image_paths}

        for future in as_completed(futures):
            file_info = futures[future]
            try:
                future.result()
            except Exception as e:
                image = cv2.imread(file_info)
                # 复制图像进行操作，避免修改原图
                output_image = image.copy()
                # 保存标记后的图像
                save_marked_image(output_image, file_info, "_plus")
                print(f"Fail to deal with: {file_info}")
